//
//  KZWkSubjectView.m
//  lg_zhinengbeikao_english
//
//  Created by 朱凯 on 2018/12/19.
//  Copyright © 2018年 zhukai. All rights reserved.
//

#import "KZWkSubjectView.h"

#import <WebKit/WebKit.h>

@interface KZWkSubjectView() <WKNavigationDelegate>
@end

@implementation KZWkSubjectView
{
    WKWebView *_webView;
}
- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        
        WKWebViewConfiguration *config = [WKWebViewConfiguration new];
        NSString *jScript = @"var meta = document.createElement('meta');\
                              meta.setAttribute('name', 'viewport');\
                              meta.setAttribute('content', 'width=device-width');\
                              document.getElementsByTagName('head')[0].appendChild(meta);";
        WKUserScript *wkUScript = [[WKUserScript alloc] initWithSource:jScript injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:true];
        WKUserContentController *wkUController = [[WKUserContentController alloc] init];
        [wkUController addUserScript:wkUScript];
        config.userContentController = wkUController;
        _webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, self.width, 1) configuration:config];
        _webView.navigationDelegate = self;
        [self addSubview:_webView];
    }
    return self;
}


- (void)setContent:(NSString *)content {
    
    _content = content;
    [_webView loadHTMLString:content baseURL:nil];
}

#pragma mark - WKNavigationDelegate
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    
    dispatch_async(dispatch_get_main_queue(), ^{
        NSString *js =[NSString stringWithFormat:@"function imgAutoFit() {\
                       var imgs = document.getElementsByTagName('img');\
                       for (var i = 0; i < imgs.length; ++i) {\
                       var img = imgs[i];\
                       img.style.maxWidth = %f;\
                       }\
                       }", self.width - 20];
        js = [NSString stringWithFormat:js, [UIScreen mainScreen].bounds.size.width];
        [webView evaluateJavaScript:js completionHandler:nil];
        [webView evaluateJavaScript:@"imgAutoFit()" completionHandler:nil];
        __weak typeof(self) wself = self;
        [webView evaluateJavaScript:@"document.body.scrollHeight" completionHandler:^(id _Nullable result, NSError * _Nullable error) {
            webView.height = [result doubleValue];
            if (wself.contentHeightDidUpdate) {
                wself.contentHeightDidUpdate(webView.bottom);
            }
        }];
    });
}
@end
